

import QueryMaterial2 from "@/components/QueryMaterial2";
import QueryUserDefine from "@/components/QueryUserDefine";
import QueryVendor from "@/components/QueryVendor";
import { s_getcommontableinfo, s_operateInfo, s_updateInfo, state2text, status2text } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components"
import { Button, Col, message, Modal, Row, Space, Tag } from "antd";
import moment from "moment";
import { useEffect, useRef, useState } from "react";
import { getSelection } from "@/services/selections";

const App:React.FC=()=>{
  const [open,setOpen]=useState(false);
  const [etype,setEtype]=useState(1);
  const [selectedRecord,setSelectRecord]=useState<DataType[]>([]);
  const [material,setMaterial]=useState<{id:any,code:any,name:any,invstd:any,invstd2:any,munit_name:any}[]>([]);
  const [vendor,setVendor]=useState<{id:any,name:any,salecategory2:any}[]>([]);
  const [userdefine,setUserDefine]=useState<{uid:any,uname:any,vlabel:any,value:any}[]>([]);
  const [material_id,setMaterial_id]=useState(0);
  const [rowno,setRowno]=useState(0);//无用属性，仅为适应组件在表格中的应用参数。

  const mtable_ref=useRef<ActionType>();
  const form_ref=useRef<ProFormInstance>();
// 价格表：新增、编辑、审核，及其他操作。其中来源为询价单（sourcetype:1）的，不允许审核。
// id,x_id,material_id,userdefine_id,userdefine_name,material_code,material_name,invstd,invstd2,munit_name,vendor_id,vendor_name,
//  pricetype,price,taxrate,netprice,minquantity,source_type,source_queryprice_mid,source_queryprice_id,
//  valid_begindate,valid_enddate,state,status,operater_id,operate_time,memo,dosample

useEffect(()=>{
   if(material.length>0){
      const m=material[0];
      form_ref.current?.setFieldsValue({
        material_id:m.id,
        material_code:m.code,
        material_name:m.name,
        invstd:m.invstd,
        invstd2:m.invstd2,
        munit_name:m.munit_name,
      });
      setMaterial_id(m.id);
   };
},[material]);

useEffect(()=>{
  if(vendor.length>0){
    const v=vendor[0];
    form_ref.current?.setFieldsValue({
      vendor_id:v.id,
      vendor_name:v.name,
      salecategory2:v.salecategory2,
    });
  }
},[vendor]);

useEffect(()=>{
  if(userdefine.length>0){
  const u=userdefine;
  var u1:any[]=[];
  var u2:any[]=[];
  u.map((item:any)=>{
    u1.push({uid:item.uid,value:item.value});
    u2.push(''.concat(item.uname,':',item.vlabel==''?item.value:item.vlabel));
  });

  form_ref.current?.setFieldsValue({
    userdefine_id:u1,
    userdefine_name:u2.toString(),
  });
}
},[userdefine]);

   interface DataType{
    id:number,x_id:number,material_id:number,userdefine_id:string,userdefine_name:string,
    material_code:string,material_name:string,invstd:string,invstd2:string,munit_name:string,
    vendor_id:number,vendor_name:string, pricetype:number,price:number,taxrate:number,netprice:number,
    minquantity:number,source_type:number,source_queryprice_mid:number,source_queryprice_id:number,
    valid_begindate:string,valid_enddate:string,state:number,status:number,operater_id:number,
    operate_time:string,memo:string,dosample:number
   }

   const columns:ProColumns<DataType>[]=[
    {dataIndex:'id',title:'ID'},{dataIndex:'x_id',hidden:true},{dataIndex:'material_id',hidden:true},
    {dataIndex:'vendor_name',title:'供应商'},
    {dataIndex:'material_code',title:'物料编码'},{dataIndex:'material_name',title:'物料名称'},{dataIndex:'invstd',title:'规格'},
    {dataIndex:'invstd2',title:'型号'},{dataIndex:'userdefine_name',title:'属性'},{dataIndex:'munit_name',title:'单位'},
    {dataIndex:'vendor_id',hidden:true},{dataIndex:'userdefine_id',hidden:true},
    {dataIndex:'price',title:'含税单价'},{dataIndex:'taxrate',title:'税率%'},{dataIndex:'netprice',title:'不含税单价'},
    {dataIndex:'minquantity',title:'最低订货量'},
    {dataIndex:'source_type',title:'订价来源',
      render:(text)=>text==1?<Tag>询价单</Tag>:text==2?<Tag>手工制单</Tag>:<>供方报价</>,
    },
    {dataIndex:'valid_begindate',title:'生效日期',
      render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
    },{dataIndex:'valid_enddate',title:'截止时间',
      render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
    },
    {dataIndex:'dosample',title:'是否含样品',
      render:(text)=>text==1?<Tag>是</Tag>:<Tag>否</Tag>,
    },
    {dataIndex:'state',title:'进度',fixed:'right',width:80,render:(text:any)=>state2text(1,text)},
    {dataIndex:'status',title:'状态',fixed:'right',width:80,render:(text:any)=>status2text(text)},
   ];


   function closeModal(){
    setOpen(false);
   }

   function add(){
     setEtype(1);
     setOpen(true);
   }

   function edit(){
    if(selectedRecord.length==0)
      message.warning('请选择要编辑的行');
    else{
      setEtype(0);
      setOpen(true);
    };
   }

   async function save(){
    const fdata2=form_ref.current?.getFieldsValue();
    const fdata={...fdata2,
                 valid_begindate:moment(moment(fdata2.valid_date[0]).toDate()).format('YYYY-MM-DD'),
                 valid_enddate:moment(moment(fdata2.valid_date[1]).toDate()).format('YYYY-MM-DD'),
    };
    // alert(JSON.stringify(fdata));
     
    const x=await s_updateInfo({source:'priceschedule',x_id:1,opearater_id:1,etype,fdata});
    if(x.success){
      message.success('保存成功');
      setEtype(1);
      setSelectRecord([]);
      mtable_ref.current?.reloadAndRest?.();
      setOpen(false);
    }else{
      message.error('保存失败，请联系管理员');
    }
    
   }

   async function operateInfo(n:number){
     // source,x_id,operater_id,otype,id
      if(selectedRecord.length==0)
             message.warning('请选择要操作的行');
       else{
             const x=await s_operateInfo({x_id:1,source:'priceschedule',operater_id:1,otype:n,id:selectedRecord[0].id});
      if(x.success){
             message.success('操作成功');
             mtable_ref.current?.reloadAndRest?.();
        }else
            message.error('操作错误，请联系管理员。');
        } 
   }
  //  表单主体==================================================================================================
    return <>
      <ProCard title='采购价格表'
           extra={<Space>
            <Button onClick={()=>add()}>新增</Button>
            <Button onClick={()=>edit()}>编辑</Button>
            <Button onClick={()=>operateInfo(5)}>审核</Button>
            <Button onClick={()=>operateInfo(6)}>取消审核</Button>
            <Button onClick={()=>operateInfo(2)}>冻结</Button>
            <Button onClick={()=>operateInfo(3)}>删除</Button>
            <Button onClick={()=>operateInfo(1)}>恢复</Button>
           </Space>}
         />
         {JSON.stringify(selectedRecord)}
           <ProTable<DataType> 
             rowKey='id'
             columns={columns}
             actionRef={mtable_ref}
             request={async ()=>{
                const x=await s_getcommontableinfo({x_id:1,source:'v_priceschedule',id:0});
                return {
                data:x.data[0],
                success:true,
               }
             }}
             rowSelection={{
              type:'radio',
              onChange(selectedRowKeys, selectedRows, info) {
                setSelectRecord(selectedRows);
              },
             }}
           />
           <Modal open={open} closable destroyOnClose onCancel={()=>closeModal()} onClose={()=>closeModal()}
              width='80%' okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
            >
            <ProCard title='价格管理'
               extra={<Space>
                <Button onClick={()=>form_ref.current?.submit()}>保存</Button>
                <Button onClick={()=>closeModal()}>取消</Button>
               </Space>}
               >
            <ProForm  submitter={false}   formRef={form_ref}
               onFinish={()=>save()}
               initialValues={etype==1?{
                              status:0,state:13,dosample:0,
                              valid_date:[moment().format('YYYY-MM-DD'),moment().format('YYYY-MM-DD')],
                              operater_id:1,taxrate:13,source_type:2,pricetype:1,
                           }
                          :{
                              ...selectedRecord[0],
                              valid_date:[moment(moment(selectedRecord[0].valid_begindate).toDate()).format('YYYY-MM-DD')
                                          ,moment(moment(selectedRecord[0].valid_enddate).toDate()).format('YYYY-MM-DD')],
                          }}
            >
                {JSON.stringify(material)}---{JSON.stringify(vendor)}
                
                <ProFormText name='id' hidden={true} />
                <ProFormText name='material_id' hidden={true} />
                <ProFormText name='userdefine_id' hidden={true} />
                <ProFormText name='vendor_id' hidden={true} />
                <ProFormText name='source_queryprice_mid' hidden={true}   />
              <Row gutter={8}>
                <Col span={8}>
                   <QueryMaterial2 type='radio' setData={setMaterial} x_id={1} />
                   <ProFormText name='material_code' label='物料编码' width={300}
                      rules={[{required:true,message:'必须选择物料信息'}]}/>
                   <ProFormText name='material_name' label='物料名称' width={300} />
                   <ProFormText name='invstd' label='规格' width={300} />
                   <ProFormText name='invstd2' label='型号' width={300}/>
                   <ProFormText name='munit_name' label='计量单位' width={300} />
                   <Space>
                       <ProFormText name='userdefine_name' label='属性' width={300}  />
                       <QueryUserDefine setData={setUserDefine} objtype={1} dotype={1} 
                            id={material_id} 
                            rowno={rowno} setRowno={setRowno}/>
                   </Space>
                </Col>
                <Col span={8}>
                    <QueryVendor setData={setVendor} type='radio'  disabled={1} x_id={1}/>
                    <ProFormText name='vendor_name' label='供应商' width={300} 
                      rules={[{required:true,message:'必须选择供应商信息'}]}
                    />
                    <ProFormText name='salecategory2' label='供货类目' width={300} />
                     <ProFormSelect name='pricetype' label='价格类型' width={300}
                           options={[{value:1,label:'批量采购'},{value:2,label:'零星采购'}]}
                           rules={[{required:true,message:'必须选择此项目'}]}
                     />
                     <ProFormSelect name='source_type' label='价格来源' width={300}
                             options={[{value:1,label:'询价单'},{value:2,label:'手工制单'}]}
                             rules={[{required:true,message:'必须输入此项目'}]}

                          />
                      
                      <ProFormDateRangePicker name='valid_date' label='生效期间'  width={300} 
                       rules={[{required:true,message:'必须输入此项目'}]}
                      />
                      <ProFormSelect name='operater_id' label='操作人' width={300} 
                      request={async ()=>{
                              var x:any=await getSelection({ source: 'base_person', x_id: 1 });
                              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                              return x2;
                             }} />
                  </Col>
                  <Col span={8}>
                       <Button>单价设置</Button>
                       <ProFormDigit name='price' label='含税单价'  width={300}
                        rules={[{required:true,message:'必须输入此项目'}]}
                         fieldProps={{
                          onChange(value) {
                            const t=form_ref.current?.getFieldValue('taxrate');
                            const v=value==null?0:value;
                            form_ref.current?.setFieldValue('netprice',v*(1-(t==null?0:t)/100));
                          },
                         }}
                       />
                       <ProFormDigit name='taxrate' label='税率%' width={300} 
                        rules={[{required:true,message:'必须输入此项目'}]}
                        fieldProps={{
                          onChange(value) {
                            const t=form_ref.current?.getFieldValue('price');
                            const v=value==null?0:value;
                            form_ref.current?.setFieldValue('netprice',t*(1-(v==null?0:v)/100));
                          },
                         }}
                       />
                       <ProFormDigit name='netprice' label='不含税单价'  width={300}
                            rules={[{required:true,message:'必须输入此项目'}]} />
                       <ProFormDigit name='minquantity' label='最低订货量'  width={300} />
                       <ProFormRadio.Group name='status' label='进度'  width={300} 
                            options={[{value:0,label:'未审核'},{value:2,label:'冻结'},
                             {value:5,label:'已审核'},{value:6,label:'弃审'},
                            {value:3,label:'删除'}]}
                        />
                  <ProFormSelect name='state' label='状态' width={300} 
                     options={[{value:1,label:'未下达'},{value:2,label:'已下达'},{value:3,label:'供方已确认'},{value:4,label:'供方已拒绝'},
                         {value:5,label:'已确认'},{value:6,label:'已拒绝'},{value:7,label:'撤销确认'},{value:8,label:'供方撤销确认'},
                         {value:9,label:'撤销下达'},{value:10,label:'未提交'},{value:11,label:'已提交'},{value:12,label:'撤销提交'},
                         {value:13,label:'已核价'},{value:14,label:'撤销核价'}
                    ]}
                />
                </Col>
                </Row>
                <Row gutter={8}>
                  <Col span={8}>
                    <ProFormRadio.Group name='dosample' label='是否含样品'
                       options={[{value:0,label:'否'},{value:1,label:'是'}]}
                      />
                  </Col>
                  <Col span={16}>
                     <ProFormTextArea name='memo' label='备注' />
                  </Col>
                </Row>
                
            </ProForm>  
            </ProCard>         
            </Modal>
      </>
}

export default App;